<template>
	<delivery-finance-preview v-if="isConfirmApply" :mode="'delivery'"></delivery-finance-preview>
	<div v-else class="m-window" v-loading="pageLoading" element-loading-text="数据加载中">
		<!-- 交货融资申请 -->
		<el-row type="flex" class="applyShort-col">
			<el-col :span="12" class="financial">
				<label class="title">可融金额：</label>
				<div class="money">
					<sup>￥</sup>
					{{ getFormatMoney }}
				</div>
			</el-col>
			<el-col :span="2" style="margin-top: 35px;">
				<el-button type="primary" @click="financing" :disabled="isBtnDisable" :loading="btnLoading">融资</el-button>
			</el-col>
			<el-tabs type="card" v-model="tabName" @tab-click="handleClick" class="orderlist-tabs">
				<el-tab-pane label="现可融货单记录" name="1">
					<ag-grid-vue
						class="ag-theme-balham ag-table"
						:gridOptions="orderGridOptions"
						:columnDefs="orderColumnDefs"
						:defaultColDef="defaultColDef"
						:rowData="orderRowData"
						v-loading="loading"
					></ag-grid-vue>
				</el-tab-pane>
				<el-tab-pane label="融资历史记录" name="2">
					<ag-grid-vue
						class="ag-theme-balham ag-table"
						:gridOptions="applyGridOptions"
						:columnDefs="applyColumnDefs"
						:defaultColDef="defaultColDef"
						:rowData="applyRowData"
						v-loading="loading"
					></ag-grid-vue>
					<pagination
						style="height:1%;"
						:config="{pageNumberChanged,pageSizeChanged,pageNumber: searchParams.pageNumber,pageSizes: [10, 30, 50, 100],justifyContent: 'flex-end'}"
						:total="totalNum"
					></pagination>
				</el-tab-pane>
			</el-tabs>
		</el-row>
		<!-- 查看订单详情弹窗 -->
		<el-dialog
			title="融资申请记录"
			:visible.sync="historyVisible"
			v-dialogDrag
			width="75%"
			class="order-detail-dialog"
		>
			<div class="historyRecord">
				<ag-grid-vue
					class="m-agTableModel ag-theme-balham"
					:gridOptions="historyGridOptions"
					:columnDefs="historyColumnDefs"
					:rowData="historyRowData"
					v-loading="historyLoading"
				></ag-grid-vue>
			</div>
			<span slot="footer" class="dialog-footer"></span>
		</el-dialog>
	</div>
</template>

<style lang="less" rel="stylesheet/less" scoped>
.applyShort-col {
	flex-direction: column;
	height: 100%;

	.financial {
		.title {
			color: #454545;
			font-size: 12px;
			font-weight: 600;
		}

		.money {
			color: #ff821f;
			font-size: 45px;
			font-weight: 600;

			sup {
				font-size: 22px;
			}
		}
	}
	.orderlist-tabs {
		margin-top: 20px;
		/deep/ .el-tabs__content {
			top: 220px;
			left: 0;
			right: 0;
			.ag-table {
				position: absolute;
				top: 0;
				bottom: 36px;
				left: 0;
				right: 0;
			}
			.pagination-box {
				position: absolute;
				bottom: 30px;
				right: 25px;
			}
		}
		/deep/ .el-tabs__item.is-top.is-active {
			background: #409eff;
			color: #fff;
		}
	}
	.history-table {
		margin-top: 35px;
		height: calc(100% - 240px);

		& label {
			font-size: 12px;
			font-weight: 600;
		}

		.ag-table {
			width: 100%;
			height: 99%;
			margin-top: 8px;
		}
	}

	.hint {
		color: red;
		font-size: 14px;
		font-weight: 600;
		font-family: "黑体";
	}
}
</style>

<script>
import { regainOriginalMoneyFormat, formatPrice } from "@/util/format.js";
import addOperation from "@/public/addOperation";
import gridOptions from "lesso-common/public/gridOptions";
import Pagination from "@/components/pagination.vue";
import DeliveryFinancePreview from "./common/deliveryFinancePreview.vue";
import { mapState, mapActions } from "vuex";
import buttonLink from "@/components/buttonLink";
/**
 * @group financeManager
 * 金货宝融资申请
*/
export default {
	name: "deliveryFinance",
	data () {
		return {
			pageLoading: true,
			defaultColDef: {
				resizable: true,
			},
			custId: this.$store.state.supplyChainFinance.custInf.custId, //获取供应商id
			isConfirmApply: false,
			searchParams: {
				pageNumber: 1,
			},
			totalNum: 0,
			availableAmount: 0,
			applyGridOptions: {},
			applyColumnDefs: [],
			applyRowData: [],
			loading: false,
			isBtnDisable: true,
			btnLoading: false,
			orderGridOptions: {},
			orderColumnDefs: [],
			orderRowData: [],
			tabName: "1",
			totalAmount: {
				available: 0,
				already: 0,
			},
			historyGridOptions: gridOptions(),
			historyColumnDefs: [],
			historyRowData: [],
			historyVisible: false,
			historyLoading: false,
			historyTotalAmount: 0,
		};
	},
	props: {
		addTab: {
			type: Function
		}
	},
	beforeMount () {
		this.getApplyOrderList();
		let queryParams = {
			supplierId: this.custId,
		};
		this.getAvailableAmount(queryParams);
		// this.getAccountQuota()
	},
	created () {
		// this.getOneOrSave()
		this.applyGridOptions = gridOptions();
		this.orderGridOptions = {
			...gridOptions(),
			pinnedBottomRowData: this.createData(1, "Bottom"),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { color: "red", "font-weight": "bold" };
				}
			},
			context: {
				componentParent: this,
			},
		};
		this.historyGridOptions = {
			...gridOptions(),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { color: "red", "font-weight": "bold" };
				}
			},
			pinnedBottomRowData: this.createBottom(1, "Bottom"),
		};
		// 现可融货单记录列配置
		this.orderColumnDefs = [
			{
				headerName: "采购订单号",
				field: "purOrdNo",
				width: 200,
				cellRenderer: buttonLink,
			},
			{
				headerName: "订单金额",
				field: "orderAmount",
				width: 120,
				valueFormatter: (params) => {
					if (!params.node.rowPinned) return formatPrice(params.value);
				},
			},
			{
				headerName: "交货金额",
				field: "deliveryAmount",
				width: 120,
				valueFormatter: (params) => {
					if (!params.node.rowPinned) return formatPrice(params.value);
				},
			},
			{
				headerName: "最早交货日期",
				field: "earliestDeliveryDate",
				width: 160,
				valueFormatter: (params) => {
					if (!params.node.rowPinned)
						return this.$utils.dateFormat("yyyy-MM-dd", params.value);
				},
			},
			{
				headerName: "已融资金额",
				field: "meltedAmount",
				width: 110,
				valueFormatter: (params) => {
					return formatPrice(params.value);
				},
			},
			{
				headerName: "已融占比",
				field: "meltdown",
				width: 110,
			},
			{
				headerName: "可融金额",
				field: "availableAmount",
				width: 110,
				valueFormatter: (params) => {
					return formatPrice(params.value);
				},
			},
			{
				headerName: "融资状态",
				field: "financingStatus",
				width: 100,
				cellRenderer: function (params) {
					if (params.value != undefined && params.value == 0) {
						return "未融";
					} else if (params.value == 1) {
						return "在融";
					}
				},
			},
			{
				headerName: "订单状态",
				field: "orderStatus",
				width: 100,
				cellRenderer: function (params) {
					if (params.value != undefined && params.value == 3) {
						return "部分交货";
					} else if (params.value == 2) {
						return "未交货";
					} else if (params.value == 4) {
						return "完全交货";
					}
				},
			},
			{
				headerName: "对账状态",
				field: "accountStatus",
				width: 100,
				cellRenderer: function (params) {
					if (params.value == 1) {
						return "未对账";
					} else if (params.value == 2) {
						return "已对账";
					}
				},
			},
		];
		// 历史融资变更列配置
		this.historyColumnDefs = [
			{
				headerName: "融资申请号",
				field: "itemNo",
				width: 140,
			},
			{
				headerName: "融资开始日期",
				field: "payDate",
				width: 140,
				valueFormatter: (params) => {
					if (!params.node.rowPinned)
						return this.$utils.dateFormat("yyyy-MM-dd", params.value);
				},
			},
			{
				headerName: "融资到期日期",
				field: "paybackDate",
				width: 140,
				valueFormatter: (params) => {
					if (!params.node.rowPinned)
						return this.$utils.dateFormat("yyyy-MM-dd", params.value);
				},
			},
			{
				headerName: "申请融资金额",
				field: "applyAmt",
				width: 140,
				valueFormatter: (params) => {
					if (!params.node.rowPinned) return formatPrice(params.value);
				},
			},
			{
				headerName: "订单融资金额",
				field: "actBalance",
				width: 140,
				valueFormatter: (params) => {
					return formatPrice(params.value);
				},
			},
			{
				headerName: "申请状态",
				field: "currentActivity",
				width: 140,
				valueFormatter: (params) => {
					if (params.value) {
						return params.value == '供应商还款' ? '待还款' : params.value
					}
				},
			},
		];
		// 融资历史列配置
		this.applyColumnDefs = [
			{
				headerName: "序号",
				field: "xuhao",
				valueGetter: "node.id",
				cellRenderer: function (params) {
					if (params.value != undefined) {
						return +params.value + 1;
					}
				},
			},
			{
				headerName: "申请编号",
				field: "itemNo",
			},
			{
				headerName: "融资开始日期",
				field: "payDate",
			},
			{
				headerName: "融资金额",
				field: "actAmt",
				valueFormatter: (params) => {
					return formatPrice(params.value);
				},
			},
			{
				headerName: "已还款金额",
				field: "paybackAmount",
				valueFormatter: (params) => {
					return formatPrice(params.value);
				},
			},
			{
				headerName: "融资产品",
				field: "finType",
			},
			{
				headerName: "还款状态",
				field: "paybackProcessStatus",
			},
		];
	},
	computed: {
		...mapState(["supplyChainFinance", "supplierApplyList"]),
		getFormatMoney () {
			return formatPrice(this.availableAmount);
		},
		accountQuota () {
			return formatPrice(this.supplierApplyList.accountQuota);
		},
	},
	methods: {
		...mapActions(["changeAccountQuota"]),
        /**
		 * @vuese
		 * 点击tab标签回调
         * @arg 参数tab为当前tab标签编码
		*/
		handleClick (tab) {
			if (tab.name == "1") {
				this.getApplyOrderList();
			} else if (tab.name == "2") {
				let params = {
					condition: {
						custId: this.custId,
					},
					current: 1,
					size: 10,
				};
				this.getApplyHistoy(params);
			}
		},
        /**
		 * @vuese
		 * 获取交货融现可融资订单记录列表数据
		*/
		getApplyOrderList () {
			let params = {
				supplierId: this.custId,
				flag: 1,
			};
			let that = this;
			that.loading = true;
			that.orderRowData = [];
			that.orderGridOptions.overlayNoRowsTemplate = "&nbsp;";
			that.totalAmount.available = 0;
			that.totalAmount.already = 0;
			setTimeout(function () {
				that.$http
					.getDeliveryOrderList(params)
					.then((response) => {
						that.loading = false;
						if (response.data.code == 1) {
							let rowDatas = response.data.rows;
							that.orderRowData = rowDatas;
							if (that.orderRowData.length == 0) {
								that.orderGridOptions.overlayNoRowsTemplate =
									"未搜索到匹配结果";
							} else {
								that.orderRowData.forEach((item) => {
									that.totalAmount.available = addOperation.accAdd(
										that.totalAmount.available,
										item.availableAmount
									);
									that.totalAmount.already = addOperation.accAdd(
										that.totalAmount.already,
										item.meltedAmount
									);
								});
								that.orderGridOptions.api.setPinnedBottomRowData(
									that.createData(1, "Bottom")
								);
							}
						} else {
							that.orderRowData = [];
							that.orderGridOptions.overlayNoRowsTemplate = "未搜索到匹配结果";
						}
					})
					.catch((errror) => {
						that.$alert("查询订单列表失败，请检查网络！", {
							confirmButtonText: "确定",
							customClass: "alertFailure",
						});
					});
			}, 500);
		},
		/**
		 * @vuese
		 * 创建现可融资货单记录底部合计栏
         * @arg 参数count为行数，prefix合计栏位置
		*/
		createData (count, prefix) {
			let result = [];
			const { available, already } = this.totalAmount;
			for (let i = 0; i < count; i++) {
				result.push({
					deliveryAmount: "合计",
					meltedAmount: formatPrice(already),
					availableAmount: formatPrice(available),
				});
			}
			return result;
		},
		/**
		* @vuese
		* 创建融资历史记录表格底部合计栏
		* @arg 参数count为行数，prefix合计栏位置
	   */
		createBottom (count, prefix) {
			let result = [];
			for (let i = 0; i < count; i++) {
				result.push({
					itemNo: "合计",
					actBalance: formatPrice(this.historyTotalAmount),
				});
			}
			return result;
		},
		/**
		 *@vuese
		 * 点击订单号获取订单融资申请记录
		 *@arg 参数是orderNo,订单号
		*/
		setClickValue (param) {
			let params = {
				orderNo: param.value,
			};
			this.historyLoading = true;
			this.historyRowData = [];
			this.historyTotalAmount = 0;
			this.$http
				.getOrderFinAmountRecord(params)
				.then(({ data }) => {
					this.historyLoading = false;
					if (data.code == 1) {
						this.historyRowData = data.rows;
						this.historyRowData.forEach((item) => {
							this.historyTotalAmount = addOperation.accAdd(
								this.historyTotalAmount,
								item.actBalance
							);
						});
						// 设置底部合计数据
						this.historyGridOptions.api.setPinnedBottomRowData(
							this.createBottom(1, "Bottom")
						);
					} else {
						this.$alert(data.info, {
							confirmButtonText: "确定",
							customClass: "alertFailure",
						});
					}
				})
				.catch((err) => {
					this.historyLoading = false;
					this.$alert("获取数据失败", {
						confirmButtonText: "确定",
						customClass: "alertFailure",
					});
				});
			this.historyVisible = true;
		},
		/**
		 * @vuese
		 * 获取交货融实时融资额度
	    */
		getAvailableAmount (params) {
			let that = this;
			this.$http
				.getDeliveryFinAmount(params)
				.then((response) => {
					setTimeout(function () {
						that.pageLoading = false;
					}, 500);
					if (response.data.code == 1) {
						this.availableAmount = response.data.rows
							? response.data.rows
							: 0.0;
					} else {
						this.availableAmount = 0;
					}
					if (this.availableAmount > 0) {
						this.isBtnDisable = false;
					}
				})
				.catch((errror) => {
					this.pageLoading = false;
					this.$alert("查询可融金额失败，请检查网络！", {
						confirmButtonText: "确定",
						customClass: "alertFailure",
					});
				});
		},
		/**
		 * @vuese
		 * 获取融资历史记录数据
	    */
		getApplyHistoy (params) {
			this.applyRowData = [];
			this.$http
				.getApplyHistoy(params)
				.then((response) => {
					this.loading = false;
					if (response.data.code == 200) {
						this.applyRowData = response.data.rows;
						this.totalNum = response.data.total;
						let gridOption = this.applyGridOptions;
						setTimeout(function () {
							let allColumnIds = [];
							if (gridOption.columnApi) {
								gridOption.columnApi.getAllColumns().forEach(function (column) {
									allColumnIds.push(column.colId);
								});
								gridOption.columnApi.autoSizeColumns(allColumnIds);
							}
						});
					} else {
						this.applyRowData = [];
						this.totalNum = 0;
					}
				})
				.catch((errror) => {
					this.$alert("查询融资历史记录失败，请检查网络！", {
						confirmButtonText: "确定",
						customClass: "alertFailure",
					});
				});
		},
		/** 
	     *@vuese 
	     * 点击融资按钮回调
	    */
		financing () {
			if (this.availableAmount <= 0) {
				this.$alert("可融金额大于0才允许申请融资", {
					confirmButtonText: "确定",
					customClass: "alertPrompt",
				});
				return;
			} else {
				this.btnLoading = true;
				this.changeAccountQuota({ supplierId: this.custId })
					.then((_) => {
						this.btnLoading = false;
						// 存在对账融资额度时给出提示
						if (regainOriginalMoneyFormat(this.accountQuota) > 0) {
							this.$confirm(
								`系统检测已有天进宝融资额度,建议优先使用天进宝<br/>天进宝融资额度:&nbsp;&nbsp;<strong style="color:#ff821f">${this.accountQuota}</strong>`,
								"提示",
								{
									confirmButtonText: "前往天进宝",
									cancelButtonText: "继续申请金货宝",
									dangerouslyUseHTMLString: true,
									closeOnPressEscape: false,
									distinguishCancelAndClose: true,
									cancelButtonClass: "finceCancelClass",
									type: "warning",
								}
							)
								.then(() => {
									this.addTab({
										cName: "天进宝",
										name: "applyShort",
										completed: false,
									});
								})
								.catch((action) => {
									if (action === "cancel") this.isConfirmApply = true;
								});
						} else {
							this.isConfirmApply = true;
						}
					})
					.catch((err) => {
						this.$alert(err, {
							confirmButtonText: "确定",
							customClass: "alertFailure",
						});
						this.btnLoading = false;
					});
			}
		},
		/** 
	     *@vuese 
	     * 页码改变回调
	     * @arg 参数为当前页码
	    */
		pageNumberChanged (pageNum) {
			if (pageNum) {
				let params = {
					condition: {
						custId: this.custId,
					},
					current: pageNum,
					size: 10,
				};
				this.getApplyHistoy(params);
			}
		},
        /** 
         *@vuese 
         * 每页显示条数改变回调
         * @arg 参数为当前显示条数
        */
		pageSizeChanged (pageSize) {
			if (pageSize) {
				let params = {
					condition: {
						custId: this.custId,
					},
					current: 1,
					size: pageSize,
				};
				this.getApplyHistoy(params);
			}
		},
		//获取客户表详情,若没有则新增
		// async getOneOrSave() {
		//     let params = this.supplyChainFinance.custInf2
		//     let that = this
		//     await that.$http.getOneOrSave(params).then(({
		//             data
		//         }) => {
		//             if (data.code == 200 && data.rows) {
		//                 //'融资状态:0-未融资,1-在天进宝  2-在月有钱'
		//                 //that.isAllowFinancing = data.rows.finStatus <= 1 ? true:false
		//             } else {
		//                 that.$alert("获取新增客户信息失败:" + data.info, {
		//                     confirmButtonText: "确定",
		//                     customClass: "alertFailure"
		//                 })
		//             }
		//         })
		//         .catch((errror) => {
		//             that.$alert("查询客户表，请检查网络！", {
		//                 confirmButtonText: "确定",
		//                 customClass: "alertFailure"
		//             })
		//         })
		// }
	},
	components: {
		Pagination,
		DeliveryFinancePreview,
	},
};
</script>
